<?php

namespace app\common\service;

use app\common\exception\BusinessException;
use app\common\helper\WxBizDataHelper;
use app\common\helper\WxHelper;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use think\facade\Config;
use Firebase\JWT\SignatureInvalidException;
use think\Exception;

class OssService
{
    /**
     * app
     * @var string
     */
    protected string $app = '';

    /**
     * host
     * @var string
     */
    protected $host = '';

    /**
     * __construct
     * @param $app
     */
    public function __construct($app)
    {
        $this->app = $app;
        $ossConfig = Config::get('oss');
        $this->host = $ossConfig['host'];
    }

    /**
     * uploadByBin
     * @param $bin
     * @param  $mime
     * @return string
     * @throws BusinessException
     * @throws Exception
     */
    public function uploadBin($bin, $mime)
    {
        // 设置接口地址
        $apiPath = $this->host . '/api/fileManage/upload';

        // 构建本地文件
        $md5 = md5($bin);
        $ds = DIRECTORY_SEPARATOR;
        $path = app()->getRootPath() . 'runtime' . $ds . 'oss_temp';
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        $filename = $path . $ds . $md5;
        if (!file_put_contents($filename, $bin)) {
            throw new Exception('oss服务构建bin文件失败');
        }

        // 组装数据
        $reqData = [
            'app' => $this->app,
            'file' => new \CURLFile($filename, $mime),
        ];
        $response = curl($apiPath, $reqData);

        // 检查响应内容
        $name = 'oss_uploadBin';
        $response = checkJsonApiResponse($name, $response, ['code', 'message', 'data']);
        if (isset($response['code']) && $response['code'] === 0) {
            $errStr = "错误码:{$response['code']},错误信息:{$response['message']}";
            throw new BusinessException("{$name}服务异常,$errStr");
        }

        // 返回
        return $response['data'];
    }
}